<template>
  <div>
    <!--补出勤录入-->
    <Dialog
      ref="d1"
      dialogCls="mydlgg"
      headerCls="mydlgg-head"
      footerCls="mydlgg-foot"
      :dialogStyle="{ width: '1000px' }"
      :modal="true"
      borderType="thin"
    >
      <div slot="header">
        <span class="headerIcon newlyAdded"></span>
        <span class="titleStyle">批量补出勤</span>
      </div>

      <div class="insidePadding">
        <!-- 这个div必须保留 -->
        <div class="fieldsetDivStyle">
          <div class="upContent">
            <div class="borderGray leftCont">
              <sidebar-dept
                :treeId="gridLeft"
                ref="leftBar"
                :checked.sync="treeChecked"
                :selected.sync="treeSelected"
                @on-select="onTreeSelect"
                @on-check="onTreeCheck"
                :checkbox="true"
              />
            </div>

            <div class="centerCont">
              <LinkButton btnCls="c1" class="rightWard" @click="addRepairUser"
                >》》
              </LinkButton>
              <LinkButton btnCls="c1" class="leftWard" @click="removeRepairUser"
                >《《
              </LinkButton>
              <p>当前人数：{{ lr.pageTotalNum }}人</p>
            </div>
            <!-- 右上角表格 -->
            <div class=" rightCont">
              <DataGrid
                class="grid-border"
                :data="lr.requestData.peopleData"
                style="height:100%;width: 100%;display: inline-grid"
                :pagination="true"
                :total="lr.pageTotalNum"
                :pageSize="100"
              >
                <GridColumn field="ck" :width="40" align="center">
                  <template slot="header" slot-scope="scope">
                    <CheckBox
                      class="cbs_15"
                      v-model="allChecked"
                      @checkedChange="onAllCheckedChange"
                    ></CheckBox>
                  </template>
                  <template slot="body" slot-scope="scope">
                    <CheckBox
                      class="cbs_15"
                      v-model="scope.row.selected"
                      @checkedChange="onCheckedChange"
                    ></CheckBox>
                  </template>
                </GridColumn>
                <GridColumn
                  field="userNo"
                  title="工号"
                  align="center"
                ></GridColumn>
                <GridColumn
                  field="userName"
                  title="姓名"
                  align="center"
                ></GridColumn>
                <GridColumn
                  field="deptName"
                  title="部门"
                  align="center"
                ></GridColumn>
              </DataGrid>
            </div>
          </div>
        </div>

        <div style="display: flex;">
          <div style="width:50%;">
            <fieldset class="fieldsetStyle" style="height:255px">
              <legend>
                <b style="color:#293569">选择日期范围</b>
              </legend>
              <!-- fieldset、legend如果需要带边框加标题的容器这俩标签必须保留 -->
              <div style="line-height: 20px;display: flex;align-items:center;">
                <label class="textbox-label" for="oneDay">单天</label>
                <RadioButton
                  inputId="oneDay"
                  class="rs_15"
                  name="groupDay"
                  value="1"
                  v-model="lr.radioDay"
                ></RadioButton>
                <label class="textbox-label" for="moreDay">多天</label>
                <RadioButton
                  inputId="moreDay"
                  class="rs_15"
                  name="groupDay"
                  value="2"
                  v-model="lr.radioDay"
                ></RadioButton>
              </div>
              <div class="fenGeXian"></div>

              <div class="fleft">
                <Label class="textbox-label">开始日期</Label>
                <DateBox
                  v-model="lr.requestData.startDate"
                  format="yyyy-MM-dd"
                  :editable="false"
                ></DateBox>
              </div>
              <div class="fleft" v-show="this.lr.radioDay == 2">
                <Label class="textbox-label">结束日期</Label>
                <DateBox
                  v-model="lr.requestData.endDate"
                  format="yyyy-MM-dd"
                  :editable="false"
                ></DateBox>
              </div>

              <div class="fenGeXian"></div>
              <div style="line-height: 20px;display: flex;align-items:center;">
                <label class="textbox-label" for="sj">按时间录入</label>
                <RadioButton
                  inputId="sj"
                  class="rs_15"
                  name="groupTime"
                  value="1"
                  v-model="lr.radioTime"
                ></RadioButton>
                <label class="textbox-label" for="banCi">按班次录入</label>
                <RadioButton
                  inputId="banCi"
                  class="rs_15"
                  name="groupTime"
                  value="2"
                  v-model="lr.radioTime"
                ></RadioButton>
              </div>
              <div class="fenGeXian"></div>

              <div v-if="lr.radioTime == '2'">
                <Label class="textbox-label">选择班次</Label>
                <ComboGrid
                  :virtualScroll="true"
                  :data="lr.banCiData"
                  :rowHeight="lr.rowHeight"
                  valueField="bh"
                  textField="mc"
                  v-model="lr.comboGridSelected"
                >
                  <DataGrid slot="grid" class="grid-border">
                    <GridColumn
                      field="bh"
                      title="编号"
                      align="center"
                    ></GridColumn>
                    <GridColumn
                      field="mc"
                      title="名称"
                      align="center"
                    ></GridColumn>
                  </DataGrid>
                </ComboGrid>
                <div v-if="lr.showTime == 1">
                  <span
                    v-for="(times, index) in lr.shidData"
                    :key="index"
                    style="margin-bottom:5px;margin-right: 10px"
                  >
<!--                    <CheckBox-->
<!--                      class="cbs_15"-->
<!--                      :inputId="times.bh + ''"-->
<!--                      :value="times.bh + ''"-->
<!--                      :multiple="true"-->
<!--                      v-model="lr.timesData"-->
<!--                    ></CheckBox>-->
                    <Label :for="times.bh + ''"
                      >{{ times.sbsj }}-{{ times.xbsj }}</Label
                    >
                  </span>
                </div>
                <span v-else>
                  <p style="color: red;">
                    请注意，选择的班次中无上下班时段,将无法提交。
                  </p>
                </span>
              </div>
              <div v-else="">
                <div style="flex:1;padding-right:20px">
                  <label class="textbox-label">上班时间</label>
                  <NumberBox
                    v-model="lr.startHour"
                    :max="47"
                    :min="-23"
                    :prefix="lr.startHour < 10 && lr.startHour >= 0 ? '0' : ''"
                    :spinners="true"
                    style="width:60px"
                  ></NumberBox>
                  <span class="inputStyle3"></span>
                  <NumberBox
                    v-model="lr.startMinute"
                    :max="59"
                    :min="0"
                    :prefix="lr.startMinute < 10 ? '0' : ''"
                    :spinners="true"
                    style="width:60px"
                  ></NumberBox>
                  <span class="inputStyle3"></span>
                  <span class="inputStyle3"></span>
                  <label class="textbox-label">下班时间</label>
                  <NumberBox
                    v-model="lr.endHour"
                    :max="47"
                    :min="-23"
                    :prefix="lr.endHour < 10 && lr.endHour >= 0 ? '0' : ''"
                    :spinners="true"
                    style="width:60px"
                  ></NumberBox>
                  <span class="inputStyle3"></span>
                  <NumberBox
                    v-model="lr.endMinute"
                    :max="59"
                    :min="0"
                    :prefix="lr.endMinute < 10 ? '0' : ''"
                    :spinners="true"
                    style="width:60px"
                  ></NumberBox>
                </div>
              </div>
            </fieldset>
          </div>
          <div style="width:50%;">
            <fieldset
            class="fieldsetStyle"
                    style="height:55px;margin-bottom:10px;"
            >
              <legend>
                <b style="color:#293569">选择审批人</b>
              </legend>
              <select-approver
                      ref="appr"
              ></select-approver>
              <div v-show="lr.isShowAppr == false">
                <p>该假类无需审批</p>
              </div>
            </fieldset>
            <fieldset
              class="fieldsetStyle"
              style="height:90px;margin-bottom:10px;"
            >
              <legend>
                <b style="color:red">*</b>
                <b style="color:#293569">事由</b>
              </legend>
              <!-- fieldset、legend如果需要带边框加标题的容器这俩标签必须保留 -->
              <TextBox
                :multiline="true"
                v-model.trim="lr.requestData.description"
                placeholder="请填写补出勤事由（必填）"
                style="width:100%;height:60px"
              ></TextBox>
            </fieldset>
            <fieldset class="fieldsetStyle" style="height:90px;">
              <legend>
                <b style="color:#293569">上传附件</b>
              </legend>
              <upload-file ref="upload1" />
              <upload-file ref="upload2" />
              <upload-file ref="upload3" />
            </fieldset>
          </div>
        </div>
      </div>

      <div slot="footer" style="border:none">
        <div class="footerDiv">
          <!-- footer、footerDiv这两个div必须保留 -->
          <LinkButton @click="saveRepair" class="saveBtn">保存</LinkButton>
          <LinkButton @click="closeaddRepair" class="cancelBtn"
            >返回
          </LinkButton>
        </div>
      </div>
    </Dialog>
    <!--错误列表弹窗-->
    <Dialog
            ref="errorXq"
            dialogCls="mydlgg"
            headerCls="mydlgg-head"
            footerCls="mydlgg-foot"
            :dialogStyle="{ width: '720px' }"
            :modal="true"
            borderType="thin"
    >
      <div slot="header">
        <span class="headerIcon newlyAdded"></span>
        <span class="titleStyle">请假错误详情</span>
      </div>
      <div class="insidePadding">
        <!-- 这个div必须保留 -->
        <fieldset class="fieldsetStyle">
          <!-- 表格容器   -->
          <div style="height: 450px">
            <ag-grid-vue
                    style="width: 100%; height: 100%;"
                    class="ag-theme-balham"
                    :rowData="lr.err.xqRowData"
                    :columnDefs="lr.err.xqColumnDefs"
            ></ag-grid-vue>
          </div>
        </fieldset>
      </div>
    </Dialog>
  </div>
</template>

<script>
import sidebarDept from "@/components/dept/sidebarDept";
// import { tableBoxHeight } from "@/api/communal";
import BdGrid from "@/components/grid";
import { AgGridVue } from "ag-grid-vue";
import dateUtil from "@/utils/dateUtils";
import user from "@/api/user";
import repair from "@/api/repairAttendance/repair";
import ztBanCi from "@/api/numberOfRuns/ztBanCi";
import ztShid from "@/api/numberOfRuns/ztShid";
import UploadFile from "@/components/uploadFile";
import selectApprover from "@/components/selectApprover";

export default {
  components: {
    sidebarDept,
    BdGrid,
    AgGridVue,
    UploadFile,
    selectApprover
  },
  name: "",
  data() {
    return {
      gridLeft: "repairTree",
      /*录入界面数据*/
      lr: {
        pageTotalNum: 0,
        rowHeight: 30,
        peopleColumns: [],

        /*单多天，1：单天，2，多天*/
        radioDay: "1",
        /*录入时间方式，1：按时间录入，2：按班次录入*/
        radioTime: "1",
        /*班次数据*/
        banCiData: [],
        /*选择的班次*/
        comboGridSelected: "",
        /*班次上下班数据*/
        shidData: [],
        /*选择的班次上下班数据*/
        timesData: [],
        /*在班次中没有配置上下班时段时，提醒*/
        showTime: 1,
        startHour: 8,
        startMinute: 0,
        endHour: 8,
        endMinute: 0,

        /*提交对象*/
        requestData: {
          //上传的文件名数组
          uploadFileNames: [],
          //补出勤原因
          description: "",
          //补出勤开始日期
          startDate: new Date(dateUtil.getDayTime()),
          //补出勤结束日期
          endDate: new Date(dateUtil.getDayTime()),
          /*补出勤人员表格  选择的人员*/
          peopleData: [],
          /*生成的上下班数段对象集合*/
          workTime: [],
          /*日期字符串集合*/
          dateList: [],
          /*选择的总人数*/
          peopleNum: 0
          //附件
        },
        err: {
            xqRowData: [],
            xqColumnDefs: [
                { headerName: "工号", field: "userNo", width: 100 },
                { headerName: "姓名", field: "userName", width: 100 },
                { headerName: "部门", field: "deptName", width: 200 },
                { headerName: "错误信息", field: "errorMsg", width: 240 }
            ]
        }
      },
      /*复选框*/
      allChecked: false,
      rowClicked: false
    };
  },
  props: {
    parentSearch: Function
  },
  mounted() {
    // tableBoxHeight();
    this.$refs.d1.close();
    this.$refs.errorXq.close();
    this.initBanCiData();
    this.startDate = dateUtil.getFirstDay();
    this.endDate = dateUtil.getLastDay();
  },
  computed: {
    checkedRows() {
      return this.lr.requestData.peopleData.filter(row => row.selected);
    }
  },
  watch: {
    "lr.comboGridSelected": {
      handler(val, oldVal) {
        this.getBanCiDetaile(val);
      }
      //immediate: true,
      // deep: true
    }
  },
  methods: {
    //初始化录入界面数据
    initLrData() {
      /*在班次中没有配置上下班时段时，提醒*/
      this.lr.showTime = 1;
      this.lr.pageTotalNum = 0;
      //选择时间初始化
      this.lr.startHour = 8;
      this.lr.startMinute = 0;
      this.lr.endHour = 8;
      this.lr.endMinute = 0;
      //选择的人员列表初始化
      this.lr.requestData.peopleData = [];
      //日期初始化
      this.lr.requestData.startDate = new Date(dateUtil.getDayTime());
      this.lr.requestData.endDate = new Date(dateUtil.getDayTime());
      //开始时间、结束时间初始化
      this.lr.radioTime = "1";
      this.lr.radioDay = "1";
      //选择的班次初始化
      this.lr.comboGridSelected = [];
      //选择的上下班初始化
      this.lr.shidData = [];
      this.lr.timesData = [];
      //补出勤原因初始化
      this.lr.requestData.description = "";
      /*生成的上下班数段对象集合*/
      this.lr.requestData.workTime = [];
      /*日期字符串集合*/
      this.lr.requestData.dateList = [];
      //附件初始化
      this.lr.requestData.uploadFileNames = [];
    },
    addRepair() {
      this.initLrData();
      this.$refs.d1.open();
    },
    /*提交补出勤*/
    saveRepair() {
      let _this = this;
      this.lr.requestData.workTime = [];
      this.getUploadFileNames();
      let startMinute = 0;
      let endMinute = 0;
      /*判断人员*/
      if (this.lr.requestData.peopleData.length > 0) {
        /*人数*/
        this.lr.requestData.peopleNum = this.lr.requestData.peopleData.length;
        //判断时间
        if (this.lr.radioDay == 1) {
          this.lr.requestData.endDate = this.lr.requestData.startDate;
        } else {
          if (this.lr.requestData.endDate < this.lr.requestData.startDate) {
            this.$messager.alert({
              title: "系统提示",
              icon: "error",
              msg: "结束日期不能早于开始日期！"
            });
            return false;
          }
        }
        //判断时间录入类型
        if (this.lr.radioTime == 1) {
          //计算开始时间、结束时间
          startMinute = dateUtil.toMinute(
            this.lr.startHour,
            this.lr.startMinute
          );
          endMinute = dateUtil.toMinute(this.lr.endHour, this.lr.endMinute);
          if (startMinute > endMinute) {
            this.$messager.alert({
              title: "系统提示",
              icon: "error",
              msg: "开始时间不能晚于结束时间！"
            });
            return false;
          }
        } else {
          let startArr = this.lr.shidData[0].sbsj.split(':');
          startMinute = dateUtil.toMinute(parseInt(startArr[0]), parseInt(startArr[1]));
          let endArr = this.lr.shidData[0].xbsj.split(':');
          endMinute = dateUtil.toMinute(parseInt(endArr[0]), parseInt(endArr[1]));
        }
        this.lr.requestData.startTime = startMinute;
        this.lr.requestData.endTime = endMinute;

        //备注必填
        if (this.lr.requestData.description=="") {
          this.$messager.alert({
            title: "系统提示",
            icon: "error",
            msg: "补出勤事由不能为空！"
          });
          return false;
        }

        this.lr.requestData.firstdApprover = this.$refs.appr.getWorkshopApprover();
        this.lr.requestData.secondApprover = this.$refs.appr.getLabourUnionApprover();
        this.lr.requestData.applyType = 2;

        if (this.lr.requestData.firstdApprover == null || this.lr.requestData.firstdApprover == 0) {
          this.$messager.alert({
            title: "系统提示",
            icon: "error",
            msg: "请选择一级审批人"
          });
          return;
        }

        if (this.lr.requestData.secondApprover == null || this.lr.requestData.secondApprover == 0) {
          this.$messager.alert({
            title: "系统提示",
            icon: "error",
            msg: "请选择二级审批人"
          });
          return;
        }

        // this.lr.requestData.dateList = dateUtil.getDateList(
        //   this.lr.requestData.startDate,
        //   this.lr.requestData.endDate
        // );
        this.lr.requestData.repairType = 0;

        this.$loading("正在保存中...");
        repair.saveRepair(this.lr.requestData).then(res => {
          this.$loading.close();
          if (res.success) {
            this.$refs.d1.close();
            this.searching();
            this.$messager.alert({
              title: "系统提示",
              icon: "success",
              msg: "保存成功！"
            });
          } else {
              if (res.result == null || res.result.length == 0) {
                  this.$messager.alert({
                      title: "系统提示",
                      icon: "error",
                      msg: res.message
                  });
              } else {
                  let pNum = res.result.length;
                  if (_this.lr.requestData.peopleData.length > pNum) {
                      this.$messager.confirm({
                          title: "系统提示",
                          msg: "保存成功！,部分人失败,点击确定查看详情。",
                          result: r => {
                          if (r) {
                              _this.$refs.d1.close();
                              this.searching();
                              _this.lr.err.xqRowData = res.result;
                              _this.$refs.errorXq.open();
                          }
                      }
                  });
                  } else {
                      this.$messager.confirm({
                          title: "系统提示",
                          msg: "保存失败！,点击确定查看详情。",
                          result: r => {
                          if (r) {
                              _this.lr.err.xqRowData = res.result;
                              _this.$refs.errorXq.open();
                          }
                      }
                  });
                  }
              }
          }
        });
      } else {
        this.$messager.alert({
          title: "系统提示",
          icon: "error",
          msg: "请选择要补出勤的人员！"
        });
      }
    },
    /*打开批量补出勤弹窗*/
    openaddRepair() {
      this.initLrData();
      this.$refs.d1.open();
    },
    closeaddRepair() {
      this.$refs.d1.close();
    },
    deleteRepair() {},
    importRepair() {},
    exportRepair() {},
    onAllCheckedChange(checked) {
      if (this.rowClicked) {
        return;
      }
      this.lr.requestData.peopleData = this.lr.requestData.peopleData.map(
        row => {
          return Object.assign({}, row, {
            selected: checked
          });
        }
      );
    },
    onCheckedChange(checked) {
      this.allChecked =
        this.checkedRows.length === this.lr.requestData.peopleData.length;
      this.rowClicked = true;
      this.$nextTick(() => (this.rowClicked = false));
    },
    /*添加人员*/
    addRepairUser() {
      let _this = this;
      let tab = this.$refs.leftBar.selectTab;
      let deptIds = null;
      let userIds = null;
      //判断tab的选择是部门还是人员
      if (tab == 1) {
        deptIds = this.$refs.leftBar.getSelectDeptIds();
        if (deptIds == null || deptIds == "") {
          this.$messager.alert({
            title: "系统提示",
            icon: "warning",
            msg: "请勾选要补出勤的部门!"
          });
          return false;
        }
      } else {
        userIds = this.$refs.leftBar.getSelectUserIds();
        if (userIds == null || userIds == "") {
          this.$messager.alert({
            title: "系统提示",
            icon: "warning",
            msg: "请勾选要补出勤的人员!"
          });
          return false;
        }
      }
      //整理请求的数据
      let param = {
        deptIds: deptIds,
        userIds: userIds
      };
      user.getUserInfoList(param).then(res => {
        if (res.code == "200") {
          let newUser = res.result;
          newUser = newUser.filter(
            row =>
              !_this.lr.requestData.peopleData.find(
                check => row.userSerial == check.userSerial
              )
          );
          _this.lr.requestData.peopleData.push(...newUser);
          _this.setPeopleTotal();
        } else {
          this.$messager.alert({
            title: "异常错误",
            icon: "error",
            msg: "获取人员异常!"
          });
        }
      });
    },
    /*移除选择的人员*/
    removeRepairUser() {
      if (this.allChecked) {
        this.lr.requestData.peopleData = [];
        this.allChecked = false;
      } else {
        this.lr.requestData.peopleData = this.lr.requestData.peopleData.filter(
          row => row.selected != true
        );
      }
      this.setPeopleTotal();
    },
    /*设置人员表格的总条数*/
    setPeopleTotal() {
      this.lr.pageTotalNum = this.lr.requestData.peopleData.length;
    },
    treeChecked() {},
    treeSelected() {},
    onTreeSelect() {},
    onTreeCheck() {},
    onFileSelect() {},
    initBanCiData() {
      let _this = this;
      ztBanCi.agAll({}).then(res => {
        if (res.code == "200") {
          _this.lr.banCiData = res.result;
        } else {
          this.$messager.alert({
            title: "异常错误",
            icon: "error",
            msg: "加载班次列表失败!"
          });
        }
      });
    },
    getBanCiDetaile(bh) {
      let _this = this;
      if (bh != "" && null != bh) {
        ztShid.period({ parent: bh }).then(res => {
          if (res.code == "200") {
            _this.lr.shidData = res.result.filter(row => {
              return row.lxrt == 0;
            });
            _this.lr.timesData = [];
            _this.lr.shidData.forEach(function(value) {
              _this.lr.timesData.push(value.bh + "");
            });
            if (_this.lr.shidData.length == 0) {
              _this.lr.showTime = 2;
            } else {
              _this.lr.showTime = 1;
            }
          } else {
            this.$messager.alert({
              title: "异常错误",
              icon: "error",
              msg: res.message
            });
          }
        });
      }
    },
    searching() {
      this.parentSearch();
    },
    //整理上传文件名集合
    getUploadFileNames() {
      this.lr.requestData.uploadFileNames = [];
      let upload1 = this.$refs.upload1.getUploadFileName();
      this.addFileNames(upload1);
      let upload2 = this.$refs.upload2.getUploadFileName();
      this.addFileNames(upload2);
      let upload3 = this.$refs.upload3.getUploadFileName();
      this.addFileNames(upload3);
    },
    //添加上传文件名到集合
    addFileNames(name) {
      if (name != null) {
        this.lr.requestData.uploadFileNames.push(name);
      }
    }
  }
};
</script>

<style scoped></style>
